# _*_ coding: utf8 _*_

from rest_framework import serializers

from common.models import Video


class ExcludeableSeri(serializers.ModelSerializer):
    excludes = []

    def __init__(self, *args, **kwargs):
        remapdata = kwargs.get('data', {})
        for (k, v) in self.remap():
            ori_value = remapdata.get(v, None)
            if ori_value:
                remapdata[k] = ori_value

        if remapdata:
            kwargs['data'] = remapdata

        super(ExcludeableSeri, self).__init__(*args, **kwargs)

        self.excludes = kwargs.get('context', {}).get('excludes', [])
        for exclude in self.excludes:
            if exclude in self.fields.keys():
                self.fields.pop(exclude)

    def remap(self):
        return []

    @property
    def safe_data(self):
        return {
            'code': 0,
            'data': self.data
        }


class VideoSeri(ExcludeableSeri):
    def create(self, validated_data):
        return Video.objects.create(**validated_data)

    def to_internal_value(self, data):

        if 'duration' not in data:
            data['duration'] = 10

        if 'title' not in data:
            data['title'] = u'演奏'
        return super(VideoSeri, self).to_internal_value(data)

    class Meta:
        model = Video
        fields = ('user', 'title', 'size', 'duration', 'url', 'cover')
